<?php

namespace app\admin\controller\finance;

use app\common\controller\Backend;
use think\Db;
use app\common\model\Config;
use app\admin\model\Admin;
use think\Loader;

/**
 * 提现记录
 *
 * @icon fa fa-circle-o
 */
class MoneyLog extends Backend
{

    /**
     * Shop模型对象
     * @var \app\admin\model\Shop
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\UserMoneyLog;
        $this->db2 = Db::connect(config('database.db2'));
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $filter = input('filter','');
            $decode = json_decode($filter,1);
            // 当前用户身份，如果是业务员，则只显示自己的活动
            $auth_group_access = Db::name('auth_group_access')->where('uid',$this->auth->id)->value('group_concat(group_id)');
            $explode = explode(',', $auth_group_access);
            $service_admin_id = [];
            $where2 = '1=1';
            if (in_array(5,$explode) && !in_array(1,$explode)) {
                $member = Db::name('admin')->where('leader',$this->auth->id)->value('group_concat(id)');
                $access_user = explode(',', $member);
                $access_user[] = $this->auth->id;
                $service_admin_id = $access_user;
                $salesman_str = implode(',', $service_admin_id);
                $where2 .= ' and order.service_admin_id in ('.$salesman_str.')';
            } elseif (in_array(3,$explode) && !in_array(1,$explode)) {// 业务员
                $service_admin_id = [$this->auth->id];
                $salesman_str = implode(',', $service_admin_id);
                $where2 .= ' and order.service_admin_id in ('.$salesman_str.')';
            }
            if (isset($decode['tran_no']) && $decode['tran_no']) {
                $play_order_nos = Db::name('play_order')->where('wm_order_sn',$decode['tran_no'])->field('play_order_no')->select();
                $play_order_no = '';
                foreach ($play_order_nos as $key => $value) {
                    $play_order_no .= $value['play_order_no'].',';
                }
                $play_order_no = trim($play_order_no,',');
                if ($play_order_nos) {
                    $where2 .= ' and user_money_log.tran_no in ('.$play_order_no.')';
                } else {
                    $where2 = ' and 1=2';
                }
            }
            if (isset($decode['service_admin_by']) && $decode['service_admin_by']) {
                $salesman_admin_id = $this->db2->name('admin')->where('nickname',$decode['service_admin_by'])->value('id');
                $where2 .= ' and order.service_admin_id ='.$salesman_admin_id;
            }

            $list = $this->db2->name('user_money_log')->alias('user_money_log')
                    ->field('user_money_log.*,user.nickname,user.mobile,order.service_admin_id,order.service_admin_by')
                    ->join('chbc_user user','user_money_log.user_id=user.id','left')
                    ->join('chbc_play_order order','user_money_log.tran_no=order.play_order_no and user_money_log.log_type=7','left')
                    ->where($where)
                    ->where($where2)
                    ->where('user_money_log.user_id=0 or user.user_type=1')
                    ->where('user_money_log.before_freeze_money=0 and user_money_log.after_freeze_money=0')
                    ->order($sort, $order)
                    ->paginate($limit);
            $list2 = $list->items();

            foreach ($list2 as &$row) {
                $user = ['nickname'=>$row['nickname'],'mobile'=>$row['mobile']];
                $row['order'] = ['service_admin_by'=>$row['service_admin_by']];
                $row['user'] = $user;
                if ($row['user_id']==0) {
                    $row['user_id'] = '-';
                } else {
                    $row['user_id'] = config('virtual_userid')+$row['user_id'];
                }
                if ($row['log_type']==7) {
                    $order = Db::name('play_order')->where('play_order_no',$row['tran_no'])->field('shop_name,play_order_no,wm_order_sn')->find();
                    $row['delete_dt'] = $order['shop_name'];
                    $row['tran_no'] = $order['wm_order_sn'];
                } else {
                    $row['delete_dt'] = '-';
                }
                $row['log_type_text'] = $this->model->getLogTypeTextAttr($row['log_type'], $row);
            }

            $result = array("total" => $list->total(), "rows" => $list2);

            return json($result);
        }
        // 当前用户身份，如果是业务员，业务员筛选那里只显示自己的名字
        $auth_group_access = Db::name('auth_group_access')->where('uid',$this->auth->id)->value('group_concat(group_id)');
        $explode = explode(',', $auth_group_access);
        $service_admin_id = [];
        if (in_array(5,$explode) && !in_array(1,$explode)) {
            $salesmanList = [];
            $member = Db::name('admin')->where('leader',$this->auth->id)->field('nickname,id')->select();
            foreach ($member as $key => $value) {
                $salesmanList[$value['nickname']] = $value['nickname'];
            }
        }elseif (in_array(1,$explode)) {
            $salesmanList = [];
            $salesman = $this->salesmanList();
            foreach ($salesman as $key => $value) {
                $salesmanList[$value['nickname']] = $value['nickname'];
            }
        } elseif (in_array(3,$explode) && !in_array(1,$explode)) {// 业务员
            $salesmanList = [];
            $salesmanList[$this->auth->nickname] = $this->auth->nickname;
        }
        $this->assignconfig(['salesmanList' => $salesmanList]);
        return $this->view->fetch();
    }

    /**
     * 生成查询所需要的条件,排序方式
     * @param mixed   $searchfields   快速查询的字段
     * @param boolean $relationSearch 是否关联查询
     * @return array
     */
    protected function buildparams($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset/d", 0);
        $limit = $this->request->get("limit/d", 999999);
        //新增自动计算页码
        $page = $limit ? intval($offset / $limit) + 1 : 1;
        if ($this->request->has("page")) {
            $page = $this->request->get("page/d", 1);
        }
        $this->request->get([config('paginate.var_page') => $page]);
        $filter = (array)json_decode($filter, true);
        
        if (isset($filter['user_id'])) {
            $filter['user_id'] = $filter['user_id']-config('virtual_userid');
        }
        if (isset($filter['tran_no'])) {
            unset($filter['tran_no']);
        }
        if (isset($filter['service_admin_by'])) {
            unset($filter['service_admin_by']);
        }
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        $where = [];
        $alias = [];
        $bind = [];
        $name = '';
        $aliasName = '';
        if (!empty($this->model) && $this->relationSearch) {
            $name = $this->model->getTable();
            $alias[$name] = Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
            $aliasName = $alias[$name] . '.';
        }
        $sortArr = explode(',', $sort);
        foreach ($sortArr as $index => & $item) {
            $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
        }
        unset($item);
        $sort = implode(',', $sortArr);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $aliasName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        $index = 0;
        foreach ($filter as $k => $v) {
            if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
                continue;
            }
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false) {
                $k = $aliasName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            //null和空字符串特殊处理
            if (!is_array($v)) {
                if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
                    $sym = strtoupper($v);
                }
                if (in_array($v, ['""', "''"])) {
                    $v = '';
                    $sym = '=';
                }
            }

            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
                    $findArr = array_values($v);
                    foreach ($findArr as $idx => $item) {
                        $bindName = "item_" . $index . "_" . $idx;
                        $bind[$bindName] = $item;
                        $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
                    }
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr, function($v){
                        return $v != '' && $v !== false && $v !== null;
                    })) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $tableArr = explode('.', $k);
                    if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias) && !empty($this->model)) {
                        //修复关联模型下时间无法搜索的BUG
                        $relation = Loader::parseName($tableArr[0], 1, false);
                        $alias[$this->model->$relation()->getTable()] = $tableArr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
            $index++;
        }
        if (!empty($this->model)) {
            $this->model->alias($alias);
        }
        $model = $this->model;
        $where = function ($query) use ($where, $alias, $bind, &$model) {
            if (!empty($model)) {
                $model->alias($alias);
                $model->bind($bind);
            }
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order, $offset, $limit, $page, $alias, $bind];
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $rows = $row;
        $rows['category'] = Config::getConfigValue('shop_category',$rows['category_no']);
        $rows['business_time'] = Config::getConfigValue('business_time',$rows['business_time_no']);
        $rows['salesman'] = '';
        if ($rows['salesman_admin_id']) {
            $rows['salesman'] = Admin::where('id',$rows['salesman_admin_id'])->value('nickname');
        }
        $this->view->assign("row", $rows);
        return $this->view->fetch();
    }

}
